package msg.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/** UDP protocol class */
public final class UDPSocket {

	/** default IP address */
	public final static String DEFIP = "127.0.0.1";
	/** default port number */
	public final static int DEFPORT = 54540;

	/** data send socket */
	private DatagramSocket socketSend;
	/** data receive socket */
	private DatagramSocket socketReceive;
	/** data address format */
	private InetAddress inetAddress;
	/** data packet */
	private DatagramPacket datagramPacket;

	/** IP address */
	private String ip;
	/** port number */
	private int port;
	/** send flag */
	private boolean sendFlag;
	/** receive flag */
	private boolean receiveFlag;

	/** default constructor */
	public UDPSocket() {
		this.ip = DEFIP;
		this.port = DEFPORT;
		this.sendFlag = false;
		this.receiveFlag = false;
	}
	
	/** constructor */
	public UDPSocket(String ip, int port) {
		this.ip = ip;
		this.port = port;
		this.sendFlag = false;
		this.receiveFlag = false;
	}

	/** method starting send socket */
	public boolean addSendSocket(String ip, int port) {
		try {
			this.ip = ip;
			this.port = port;
			this.socketSend = new DatagramSocket();
			this.inetAddress = InetAddress.getByName(this.ip);
			this.sendFlag = true;

		} catch (Exception ex) {
			System.err.println(ex.getMessage());
			this.sendFlag = false;
		}
		return this.sendFlag;
	}

	/** method starting receive socket */
	public boolean addReceiveSocket(int port) {
		try {
			this.socketReceive = new DatagramSocket(port);
			this.receiveFlag = true;

		} catch (Exception ex) {
			System.err.println(ex.getMessage());
			this.receiveFlag = false;
		}
		return this.receiveFlag;
	}

	/** method send byte data gram packed */
	public boolean sendByte(byte buffer[]) {
		try {
			if (this.sendFlag) {
				this.datagramPacket = new DatagramPacket(buffer, buffer.length, this.inetAddress, this.port);
				this.socketSend.send(datagramPacket);
			}
		} catch (Exception ex) {
			System.err.println(ex.getMessage());
			this.sendFlag = false;
		}
		return this.sendFlag;
	}

	/** method receive byte data gram packed */
	public byte[] receiveByte() {
		try {
			byte buffer[] = new byte[20000];

			if (this.receiveFlag) {
				this.datagramPacket = new DatagramPacket(buffer, buffer.length);
				this.socketReceive.receive(datagramPacket);
				return datagramPacket.getData();
			}
		} catch (Exception ex) {
			System.err.println(ex.getMessage());
			this.receiveFlag = false;
		}
		return null;
	}
	
	/** method send data gram packed */
	public boolean send(String msg) {
		return this.sendByte(msg.getBytes());
	}
	
	/** method receive data gram packed */
	public String receive() {
		return new String(this.receiveByte()).trim();
	}
}